<template>
  <div class="data-list-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <div class="table-title">数据列表</div>
        <div class="table-operations">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 新增
          </el-button>
          <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
            <i class="el-icon-delete"></i> 批量删除
          </el-button>
          <el-button @click="handleExport">
            <i class="el-icon-download"></i> 导出
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="category" label="分类" />
        <el-table-column prop="date" label="创建日期" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增数据' : '编辑数据'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="类别一" value="category1" />
            <el-option label="类别二" value="category2" />
            <el-option label="类别三" value="category3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'DataList',
  setup() {
    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      status: '',
      dateRange: []
    })

    // 表格数据
    const tableData = ref([])
    const loading = ref(false)
    const total = ref(0)
    const pageSize = ref(10)
    const currentPage = ref(1)
    const selectedRows = ref([])

    // 对话框
    const dialogVisible = ref(false)
    const dialogType = ref('add') // 'add' 或 'edit'
    const formRef = ref(null)
    const formData = reactive({
      id: '',
      name: '',
      category: '',
      status: 'active',
      description: '',
      date: ''
    })
    const formRules = {
      name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      category: [{ required: true, message: '请选择分类', trigger: 'change' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }

    // 获取表格数据
    const fetchData = () => {
      loading.value = true
      // 模拟API请求
      setTimeout(() => {
        const mockData = []
        for (let i = 1; i <= 20; i++) {
          mockData.push({
            id: i,
            name: `数据项 ${i}`,
            category: `类别${i % 3 + 1}`,
            date: `2025-09-${10 + i}`,
            status: i % 2 === 0 ? 'active' : 'inactive',
            description: `这是数据项 ${i} 的描述信息`
          })
        }
        tableData.value = mockData
        total.value = 100 // 模拟总数据量
        loading.value = false
      }, 500)
    }

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchData()
    }

    // 重置搜索
    const resetSearch = () => {
      searchForm.keyword = ''
      searchForm.status = ''
      searchForm.dateRange = []
      handleSearch()
    }

    // 表格选择变化
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }

    // 分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchData()
    }

    // 页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchData()
    }

    // 新增
    const handleAdd = () => {
      dialogType.value = 'add'
      formData.id = ''
      formData.name = ''
      formData.category = ''
      formData.status = 'active'
      formData.description = ''
      formData.date = ''
      dialogVisible.value = true
    }

    // 编辑
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      formData.id = row.id
      formData.name = row.name
      formData.category = row.category
      formData.status = row.status
      formData.description = row.description
      formData.date = row.date
      dialogVisible.value = true
    }

    // 删除
    const handleDelete = (row) => {
      ElMessageBox.confirm(`确定要删除 ${row.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        const index = tableData.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          tableData.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      }).catch(() => {})
    }

    // 批量删除
    const handleBatchDelete = () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
      }
      
      ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟批量删除操作
        const ids = selectedRows.value.map(item => item.id)
        tableData.value = tableData.value.filter(item => !ids.includes(item.id))
        ElMessage.success('批量删除成功')
      }).catch(() => {})
    }

    // 导出
    const handleExport = () => {
      ElMessage.success('数据导出成功')
    }

    // 提交表单
    const submitForm = () => {
      formRef.value?.validate((valid) => {
        if (valid) {
          if (dialogType.value === 'add') {
            // 模拟新增操作
            const newItem = {
              id: tableData.value.length + 1,
              name: formData.name,
              category: formData.category,
              status: formData.status,
              description: formData.description,
              date: new Date().toISOString().split('T')[0]
            }
            tableData.value.unshift(newItem)
            ElMessage.success('新增成功')
          } else {
            // 模拟编辑操作
            const index = tableData.value.findIndex(item => item.id === formData.id)
            if (index !== -1) {
              tableData.value[index] = {
                ...tableData.value[index],
                name: formData.name,
                category: formData.category,
                status: formData.status,
                description: formData.description
              }
              ElMessage.success('编辑成功')
            }
          }
          dialogVisible.value = false
        }
      })
    }

    onMounted(() => {
      fetchData()
    })

    return {
      searchForm,
      tableData,
      loading,
      total,
      pageSize,
      currentPage,
      selectedRows,
      dialogVisible,
      dialogType,
      formRef,
      formData,
      formRules,
      handleSearch,
      resetSearch,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      handleBatchDelete,
      handleExport,
      submitForm
    }
  }
}
</script>

<style scoped>
.data-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}

.table-operations {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>